package cn.tedu.weibo.service.impl;

import cn.tedu.weibo.common.response.JsonResult;
import cn.tedu.weibo.common.response.StatusCode;
import cn.tedu.weibo.exception.ServiceException;
import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.dto.UserRegDTO;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.security.CustomUserDetails;
import cn.tedu.weibo.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class UserService implements IUserService {
    @Autowired
    UserMapper mapper;
    @Override
    public void reg(UserRegDTO userRegDTO) {
        UserVO userVO = mapper.selectByUsername(userRegDTO.getUsername());
        if (userVO!=null){
            //三层架构中，在Service层不能直接给客户端响应数据，
            //出现业务异常情况通过抛出自定义Service异常的方式在全局处理器中对异常进行捕获
            //并响应给客户端
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        mapper.insert(user);
    }

    @Autowired
    AuthenticationManager manager;
    @Override
    public CustomUserDetails login(UserLoginDTO userLoginDTO) {
        //通过认证管理器 开启认证流程, 返回值是认证结果
        Authentication result = manager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        userLoginDTO.getUsername(),userLoginDTO.getPassword()));
        //把认证结果保存到Security框架的上下文当中
        SecurityContextHolder.getContext().setAuthentication(result);
        //从认证结果中得到当事人(当前登录成功的,装着用户信息的对象)
        CustomUserDetails ud = (CustomUserDetails) result.getPrincipal();
        System.out.println(ud.getNickname());
        return ud;
    }

    @Override
    public void logout() {
        //从Security框架的上下文中清除登录认证信息
        SecurityContextHolder.clearContext();
    }

}
